package org.nch.videoLauncher.repository;

import org.hibernate.Session;
import org.nch.videoLauncher.domain.PlaybackEvent;
import org.nch.videoLauncher.domain.VideoItem;
import org.nch.videoLauncher.domain.Profile;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: bill
 * Date: Dec 13, 2008
 * Time: 12:33:40 PM
 * To change this template use File | Settings | File Templates.
 */
public class PlaybackEventRepository {

    public PlaybackEventRepository(){

    }

    public PlaybackEvent getById(Integer id){

        PlaybackEvent playbackEvent;
        Session session = HibernateUtil.getSession();

        try {
            playbackEvent = (PlaybackEvent) session.load(PlaybackEvent.class, id);
        }
        finally {
            session.close();
        }

        return playbackEvent;
    }

    public List<PlaybackEvent> getAll(){

        Session session = HibernateUtil.getSession();
        List<PlaybackEvent> playbackEvents;

        try {
            playbackEvents = session.createQuery("from PlaybackEvent as pbe order by pbe.date desc").list();
        }
        finally {
            session.close();
        }

        return playbackEvents;
    }

    public List<PlaybackEvent> getForVideoItem(VideoItem vi){

        Session session = HibernateUtil.getSession();
        List<PlaybackEvent> playbackEvents;

        try {
            playbackEvents = session.createQuery("from PlaybackEvent as pbe where pbe.videoItem = ? order by pbe.date desc").setParameter(0, vi).list();
        }
        finally {
            session.close();
        }
        return playbackEvents;
         
    }

    public List<PlaybackEvent> getForProfile(Profile profile){

        Session session = HibernateUtil.getSession();
        List<PlaybackEvent> playbackEvents;

        try {
            playbackEvents = session.createQuery("from PlaybackEvent as pbe where pbe.profile = ?").setParameter(0, profile).list();
        }
        finally {
            session.close();
        }
        return playbackEvents;
    }

    public PlaybackEvent persist(PlaybackEvent pbe){

        Session session = HibernateUtil.getSession();

        try {

            session.beginTransaction();
            session.saveOrUpdate(pbe);
            session.getTransaction().commit();
        }
        finally {
            session.flush();
            session.close();
        }

        return pbe;
    }




}
